package com.yhyr.mybatis.dynamic.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.yhyr.mybatis.dynamic.datasource.DataSourceContextHolder;
import com.yhyr.mybatis.dynamic.datasource.DynamicDataSource;
import com.yhyr.mybatis.dynamic.domain.DbInfo;
import com.yhyr.mybatis.dynamic.services.DBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
@Order(1)
public class MultiDataSourceConfig implements ApplicationRunner {

    @Autowired
    DBService dbService;

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        //动态加载数据源
        DataSourceContextHolder.setDBType("master");
        List<DbInfo> dbInfoList = dbService.getDBInfoList();

        if (dbInfoList != null && dbInfoList.size() > 0) {
            Map<Object, Object> dataSourceMap = DynamicDataSource.getInstance().getDataSourceMap();

            for (DbInfo dbInfo : dbInfoList) {
                DruidDataSource druidDataSource = new DruidDataSource();
                druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
                druidDataSource.setUrl("jdbc:mysql://" + dbInfo.getDbIp() + ":" + dbInfo.getDbPort() + "/" + dbInfo.getDbName() + "?characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false");
                druidDataSource.setUsername(dbInfo.getDbUser());
                druidDataSource.setPassword(dbInfo.getDbPasswd());

                dataSourceMap.put(dbInfo.getDbName(), druidDataSource);
                DynamicDataSource.getInstance().setTargetDataSources(dataSourceMap);
            }
        }
        System.out.println("Load DynamicDataSource Complete:" + DynamicDataSource.getInstance().getDataSourceMap().toString());
    }
}
